/*****************************************************************************************************
 * DESC			:	API函数定义
 * Author		:	Steven.Li
 * Datetime		:	2017-07-06
 * ***************************************************************************************************
 * 函数组			函数名称			函数作用
 *
 * 接口函数
 * 			           queryKindData		           按条件获取条款信息
 *                                             initRiskSelect                            初始化险种下拉框信息
 * ***************************************************************************************************
 */

import Constant from "../constant";
import Validations from "../validations";

const PlanAPI = {

            initRiskSelect(_this) {
                    $.ajax({
                    type: 'POST',
                    url: Constant.urls.queryAllPrpdRisk,
                    dataType: 'json',
                    success: function(data) {
                        if(data.state === 3) {
                            _this.$router.push('/login');
                            _this.$message({type: 'error',message: data.result});
                            return false;
                        }
                        if(data.state == 0) {
                             _this.riskOptions = data.result;
                        } else {
                            alert(data.result);
                        }
                    }
                });
            },

            initRiskKindSelect(_this) {
                    $.ajax({
                    type: 'POST',
                    url: Constant.urls.queryRiskKind,
                    data: {
                        riskCode: _this.risk.riskcode,
                        riskVersion: _this.risk.riskversion
                    },
                    dataType: 'json',
                    success: function(data) {
                        if(data.state === 3) {
                            _this.$router.push('/login');
                            _this.$message({type: 'error',message: data.result});
                            return false;
                        }
                        if(data.state == 0) {
                             _this.kindOptions = data.result;
                        } else {
                            _this.$message({type: 'error',message: '调用接口错误！'});
                        }
                    }
                });
            },

            initKindItems(_this) {
                _this.loading = true;
                $.ajax({
                    type: 'POST',
                    url: Constant.urls.queryKindItems,
                    data: {
                        plancode: _this.formData.plancode
                    },
                    dataType: 'json',
                    success: function(data) {
                        _this.loading = false;
                        if(data.state === 3) {
                            _this.$router.push('/login');
                            _this.$message({type: 'error',message: data.result});
                            return false;
                        }
                        if(data.state == 0) {
                             let kinds = data.result.kinds;
                             let items = data.result.items;
                             let kinditems = data.result.kinditems;

                             _this.formData.kinds = kinds;
                             _this.formData.items = items;
                             _this.formData.kinditems = kinditems;
                             _this.formData.delflag = data.result.delflag;

                             let kindcodes = '';
                            for(let i = 0; i <kinds.length - 1; i++) {
                                kindcodes += kinds[i].kindcode + ",";
                            }
                            if(kinds.length > 0) {
                               kindcodes += kinds[kinds.length - 1].kindcode;
                            }
                             _this.formData.kindcodes = kindcodes;

                             let itemcodes = '';
                            for(let i = 0; i <items.length - 1; i++) {
                               itemcodes += items[i].itemcode + ",";
                            }
                            if(items.length > 0) {
                                itemcodes+= items[items.length - 1].itemcode;
                            }
                            _this.formData.itemcodes = itemcodes;

                        } else {
                            _this.$message({type: 'error',message: '调用接口错误！'});
                        }
                    }
                });
            },

            initKindItems2(_this) {
                _this.loading = true;
                $.ajax({
                    type: 'POST',
                    url: Constant.urls.queryKindItems2,
                    data: {
                        plancode: _this.formData.plancode
                    },
                    async: false,
                    dataType: 'json',
                    success: function(data) {
                        _this.loading = false;
                        if(data.state === 3) {
                            _this.$router.push('/login');
                            _this.$message({type: 'error',message: data.result});
                            return false;
                        }
                        if(data.state == 0) {
                          let propsGroup = data.result.propsGroup;
                          let kindsGroup = data.result.kindsGroup;
                          let itemsGroup = data.result.itemsGroup;
                          let kinditemsGroup = data.result.kinditemsGroup;

                          for (let i = 0; i < propsGroup.length; i++) {
                            _this.propsIndex.push(propsGroup[i].length);
                            for (let j = 0; j < propsGroup[i].length; j++) {
                              propsGroup[i][j].rowId = j + 1;
                            }
                          }

                          _this.formData.propsGroup = propsGroup;
                          _this.formData.kindsGroup = kindsGroup;
                          _this.formData.itemsGroup = itemsGroup;
                          _this.formData.kinditemsGroup = kinditemsGroup;
                          _this.formData.delflag = data.result.delflag;


                          for (let i = 0; i < kindsGroup.length; i++) {
                            let kindcodes = '';
                            for (let j = 0; j < kindsGroup[i].length - 1; j++) {
                              kindcodes += kindsGroup[i][j].kindcode + ",";
                            }
                            if (kindsGroup[i].length > 0) {
                              kindcodes += kindsGroup[i][kindsGroup[i].length - 1].kindcode;
                            }
                            _this.formData.kindcodesGroup.push(kindcodes);
                          }

                          for (let i = 0; i < itemsGroup.length; i++) {
                            let itemcodes = '';
                            for (let j = 0; j < itemsGroup[i].length - 1; j++) {
                              itemcodes += itemsGroup[i][j].itemcode + ",";
                            }
                            if (itemsGroup[i].length > 0) {
                              itemcodes += itemsGroup[i][itemsGroup[i].length - 1].itemcode;
                            }
                            _this.formData.itemcodesGroup.push(itemcodes);
                          }

                        } else {
                            _this.$message({type: 'error',message: '调用接口错误！'});
                        }
                    }
                });
            },

            openAddDialog(_this) {
                    _this.showIsConfigPropsDialog = true;
            },

            openEditDialog(_this) {
                    if (_this.selectedRows.length > 1) {
                        _this.$message({type: 'error',message: '只能选择一行数据进行编辑'});
                        return;
                    } else if (_this.selectedRows.length < 1) {
                        _this.$message({type: 'error',message: '请选择方案！'});
                        return;
                    }
                    if(_this.selectedRows[0].plancode.length !== 13) {
                        _this.$message({type: 'error',message: '只能对新方案进行操作，老方案请联系线下人员操作!'});
                        return;
                    }
                    if (this.isPlanOfRating(_this.selectedRows[0].plancode)) {
                        _this.showEdit2Dialog = true;
                    } else {
                        _this.showEditDialog = true;
                    }
            },
            isPlanOfRating(plancode){
              let response = false;
              $.ajax({
                type: 'POST',
                url: Constant.urls.queryPlansub,
                data: {
                  plancode: plancode,
                },
                async: false,
                dataType: 'json',
                success: function(data) {
                  if(data.state === 3) {
                    _this.$router.push('/login');
                    _this.$message({type: 'error',message: data.result});
                    return false;
                  }
                  if(data.state == 0) {
                    response = data.result;
                  } else {
                    _this.$message({type: 'error',message: '调用接口错误！'});
                  }
                }
              });
              return response;
            },
            openCopyDialog(_this) {
                    if (_this.selectedRows.length > 1) {
                        _this.$message({type: 'error',message: '只能选择一行数据进行编辑'});
                        return;
                    } else if (_this.selectedRows.length < 1) {
                        _this.$message({type: 'error',message: '请选择方案！'});
                        return;
                    }
                    if(_this.selectedRows[0].plancode.length !== 13) {
                            _this.$message({type: 'error',message: '只能对新方案进行操作，老方案请联系线下人员操作!'});
                            return;
                    }
                    if (this.isPlanOfRating(_this.selectedRows[0].plancode)) {
                        _this.showCopy2Dialog = true;
                    } else {
                        _this.showCopyDialog = true;
                    }
            },

            openLinkPropsDialog(_this) {
                     if (_this.selectedRows.length > 1) {
                        _this.$message({type: 'error',message: '只能选择一行数据进行配置'});
                        return;
                    } else if (_this.selectedRows.length < 1) {
                        _this.$message({type: 'error',message: '请选择方案！'});
                        return;
                    }
                    //if(_this.selectedRows[0].plancode.length !== 13) {
                    //    _this.$message({type: 'error',message: '只能对新方案进行操作，老方案请联系线下人员操作!'});
                    //    return;
                    //}
                    _this.showLinkPropsDialog = true;
            },

             planFormValidation(_this) {
                //添加方案，表单非空校验
                let requiredFields = [];
                requiredFields.push( _this.formData.plantype);
                // requiredFields.push( _this.formData.plancode);
                requiredFields.push( _this.formData.plancname);
                requiredFields.push( _this.formData.planename);
                requiredFields.push( _this.formData.validstatus);
                requiredFields.push( _this.formData.kindcodes);
                requiredFields.push( _this.formData.delflag);
                requiredFields.push( _this.formData.applycomcode);
                if(!Validations.required(requiredFields,_this)) {
                        return false;
                }

                let kinditems = _this.formData.kinditems;
                requiredFields = [];
                for (let i = 0; i < kinditems.length; i++) {
                    requiredFields.push(kinditems[i].quantity);
                    requiredFields.push(kinditems[i].currency);
                    requiredFields.push(kinditems[i].amount);
                    requiredFields.push(kinditems[i].unitamount);
                    requiredFields.push(kinditems[i].premium);
                    requiredFields.push(kinditems[i].unitpremium);
                    requiredFields.push(kinditems[i].rate);
                    requiredFields.push(kinditems[i].discount);
                }

                if(!Validations.required(requiredFields,_this)) {
                        return false;
                }

                return true;
            },

            planFormValidation2(_this) {
              //添加方案，表单非空校验
              let requiredFields = [];
              requiredFields.push(_this.formData.plantype);
              requiredFields.push(_this.formData.plancname);
              requiredFields.push(_this.formData.planename);
              requiredFields.push(_this.formData.validstatus);
              requiredFields.push(_this.formData.delflag);
              requiredFields.push(_this.formData.autoundwrt);
              requiredFields.push(_this.formData.applycomcode);
              if (!Validations.required(requiredFields, _this)) {
                return false;
              }

              if (_this.formData.propsGroup.length <= 0) {
                _this.$message({type: 'error',message: '请配置【费率因子】'});
                return false;
              } else {
                for (let i = 0; i < _this.formData.propsGroup.length; i++) {
                  let props = _this.formData.propsGroup[i];
                  if(props.length <= 0) {
                    _this.$message({type: 'error',message: '因子组【'+i+'】，请添加因子！'});
                    return false;
                  }
                }
              }
              if (_this.formData.kindcodesGroup.length <= 0) {
                _this.$message({type: 'error',message: '条款代码必填！'});
                return false;
              } else {
                for (let i = 0; i < _this.formData.kindcodesGroup.length; i++) {
                  let kindcodes = _this.formData.kindcodesGroup[i];
                  if(kindcodes === null || kindcodes === '' || typeof kindcodes === 'undefined') {
                    _this.$message({type: 'error',message: '因子组【'+i+'】,条款代码必填！'});
                    return false;
                  }
                }
                for (let i = 0; i < _this.formData.kinditemsGroup.length; i++) {
                  let kinditems = _this.formData.kinditemsGroup[i];
                  requiredFields = [];
                  for (let j = 0; j < kinditems.length; j++) {
                    requiredFields.push(kinditems[j].quantity);
                    requiredFields.push(kinditems[j].currency);
                    requiredFields.push(kinditems[j].amount);
                    requiredFields.push(kinditems[j].unitamount);
                    requiredFields.push(kinditems[j].premium);
                    requiredFields.push(kinditems[j].unitpremium);
                    requiredFields.push(kinditems[j].rate);
                    requiredFields.push(kinditems[j].discount);
                  }
                  if(!Validations.required(requiredFields,_this)) {
                    _this.$message({type: 'error',message: '因子组【'+i+'】-【保额保费】，带“*”字段必填！'});
                    return false;
                  }
                }
              }



              return true;
            },

            add(_this) {
                _this.loading = true;
                let api = this;

                if (!api.planFormValidation(_this)) {
                    _this.loading = false;
                    return ;
                }

              $.ajax({
                type: 'POST',
                url: Constant.urls.addPlan,
                data: JSON.stringify(_this.formData),
                dataType: 'json',
                contentType: 'application/json',
                success: function (data) {
                  if (data.state === 3) {
                    _this.$router.push('/login');
                    _this.$message({type: 'error', message: data.result});
                    return false;
                  }
                  if (data.state == 0) {
                    _this.$message({type: 'success', message: '新增方案成功!'});
                    _this.off();
                    api.query(_this.$parent);
                  } else {
                    if (data.result.length > 40) {
                      alert(data.result);
                    } else {
                      _this.$message({type: 'error', message: data.result});
                    }
                  }
                },
                complete: function (XMLHttpRequest, textStatus) {
                  if (textStatus == 'timeout') {
                    _this.$message({type: 'error', message: '服务器连接超时!'});
                  }
                },
                error: function (XMLHttpRequest, textStatus) {
                  console.log(XMLHttpRequest);
                  console.log(textStatus);
                  _this.$message({type: 'error', message: '服务器错误!'});
                }
              });
                _this.loading = false;
            },

            add2(_this) {
              _this.loading = true;
              let api = this;

              if (!api.planFormValidation2(_this)) {
                _this.loading = false;
                return;
              }

              $.ajax({
                type: 'POST',
                url: Constant.urls.addPlan2,
                data: JSON.stringify(_this.formData),
                dataType: 'json',
                contentType: 'application/json',
                success: function (data) {
                  if (data.state === 3) {
                    _this.$router.push('/login');
                    _this.$message({type: 'error', message: data.result});
                    return false;
                  }
                  if (data.state == 0) {
                    _this.$message({type: 'success', message: '新增方案成功!'});
                    _this.off();
                    api.query(_this.$parent);
                  } else {
                    if (data.result.length > 40) {
                      alert(data.result);
                    } else {
                      _this.$message({type: 'error', message: data.result});
                    }
                  }
                },
                complete: function (XMLHttpRequest, textStatus) {
                  if (textStatus == 'timeout') {
                    _this.$message({type: 'error', message: '服务器连接超时!'});
                  }
                },
                error: function (XMLHttpRequest, textStatus) {
                  console.log(XMLHttpRequest);
                  console.log(textStatus);
                  _this.$message({type: 'error', message: '服务器错误!'});
                }
              });
              _this.loading = false;
            },

            edit(_this) {
                    let api = this;

                    if (!api.planFormValidation(_this)) {
                        return ;
                    }

                    _this.$confirm('此操作将修改该方案, 是否继续?', '提示', {
                        confirmButtonText: '确定',
                        cancelButtonText: '取消',
                        type: 'warning'
                    }).then(() => {
                        _this.loading = true;
                         $.ajax({
                            type: 'POST',
                            url: Constant.urls.editPlan,
                            data: JSON.stringify(_this.formData),
                            dataType: 'json',
                            contentType: 'application/json',
                            success: function(data) {
                                if(data.state === 3) {
                                    _this.$router.push('/login');
                                    _this.$message({type: 'error',message: data.result});
                                    return false;
                                }
                                if(data.state == 0) {
                                    _this.$message({type: 'success',message: '方案修改成功!'});
                                    _this.off();
                                    api.query(_this.$parent);
                                } else {
                                    if (data.result.length > 40) {
                                        alert(data.result);
                                    } else {
                                        _this.$message({type: 'error',message: data.result});
                                    }
                                }
                            },
                            complete:function(XMLHttpRequest,textStatus){  
                                if(textStatus=='timeout'){
                                    _this.$message({type: 'error',message: '服务器连接超时!'});
                                }
                            },  
                            error:function(XMLHttpRequest, textStatus){  
                                console.log(XMLHttpRequest);
                                console.log(textStatus);
                               _this.$message({type: 'error',message: '服务器错误!'});
                            }
                        });
                        _this.loading = false;
                    }).catch(() => {
                        _this.$message({type: 'info',message: '已取消修改'});
                    });
            },

            edit2(_this) {
                    let api = this;

                    if (!api.planFormValidation2(_this)) {
                        return ;
                    }

                    _this.$confirm('此操作将修改该方案, 是否继续?', '提示', {
                        confirmButtonText: '确定',
                        cancelButtonText: '取消',
                        type: 'warning'
                    }).then(() => {
                        _this.loading = true;
                         $.ajax({
                            type: 'POST',
                            url: Constant.urls.editPlan2,
                            data: JSON.stringify(_this.formData),
                            dataType: 'json',
                            contentType: 'application/json',
                            success: function(data) {
                                if(data.state === 3) {
                                    _this.$router.push('/login');
                                    _this.$message({type: 'error',message: data.result});
                                    return false;
                                }
                                if(data.state == 0) {
                                    _this.$message({type: 'success',message: '方案修改成功!'});
                                    _this.off();
                                    api.query(_this.$parent);
                                } else {
                                    if (data.result.length > 40) {
                                        alert(data.result);
                                    } else {
                                        _this.$message({type: 'error',message: data.result});
                                    }
                                }
                            },
                            complete:function(XMLHttpRequest,textStatus){  
                                if(textStatus=='timeout'){
                                    _this.$message({type: 'error',message: '服务器连接超时!'});
                                }
                            },  
                            error:function(XMLHttpRequest, textStatus){  
                                console.log(XMLHttpRequest);
                                console.log(textStatus);
                               _this.$message({type: 'error',message: '服务器错误!'});
                            }
                        });
                        _this.loading = false;
                    }).catch(() => {
                        _this.$message({type: 'info',message: '已取消修改'});
                    });
            },

            query(_this) {
                _this.loading = true;
                $.ajax({
                    type: 'POST',
                    url: Constant.urls.queryPrpdRiskPlan,
                    data: _this.formData,
                    dataType: 'json',
                    success: function(data) {
                        _this.loading = false;
                        if(data.state === 3) {
                            _this.$router.push('/login');
                            _this.$message({type: 'error',message: data.result});
                            return false;
                        }
                        if(data.state == 0) {
                            _this.tableData = data.result;
                            _this.total = data.total;
                        } else {
                          alert(data.result);
                        }
                    },
                    complete:function(XMLHttpRequest,textStatus){  
                        if(textStatus=='timeout'){
                            _this.$message({type: 'error',message: '服务器连接超时!'});
                        }
                        _this.loading = false;
                    },  
                    error:function(XMLHttpRequest, textStatus){  
                        console.log(XMLHttpRequest);
                        console.log(textStatus);
                       _this.$message({type: 'error',message: '服务器错误!'});
                       _this.loading = false;
                    }
                });
                 setTimeout(function(){
                    _this.isSortRequest = true;
                },500);
            },
            newPlanCode(_this) {
                $.ajax({
                    type: 'POST',
                    url: Constant.urls.generatePlanCode,
                    data: {
                       riskcode : _this.formData.risk.riskcode,
                    },
                    dataType: 'json',
                    success: function(data) {
                        if(data.state === 3) {
                            _this.$router.push('/login');
                            _this.$message({type: 'error',message: data.result});
                            return false;
                        }
                        if(data.state == 0) {
                            _this.formData.plancode = data.result;
                        } else {
                          alert(data.result);
                        }
                    }
                });
            },
            getItemOptions(_this) {
                let postData = {
                       risk : _this.risk,
                       kinds: _this.kinds
                }
                $.ajax({
                    type: 'POST',
                    url: Constant.urls.getItemLinked,
                    data: JSON.stringify(postData),
                    dataType: 'json',
                    contentType : 'application/json',
                    success: function(data) {
                        if(data.state === 3) {
                            _this.$router.push('/login');
                            _this.$message({type: 'error',message: data.result});
                            return false;
                        }
                        if(data.state == 0) {
                            _this.itemOptions = data.result;
                        } else {
                           alert(data.result);
                        }
                    }
                });
            },
             queryPrpdCompany(_this) {
                $.ajax({
                    type: 'POST',
                    url: Constant.urls.queryPrpdCompany,
                    data: _this.formData,
                    dataType: 'json',
                    success: function(data) {
                        if(data.state === 3) {
                            _this.$router.push('/login');
                            _this.$message({type: 'error',message: data.result});
                            return false;
                        }
                        if(data.state == 0) {
                            _this.tableData = data.result;
                            _this.total = data.total;
                        } else {
                           _this.$message({type: 'error',message: '调用接口错误！'});
                        }
                    }
                });
            },
            openPlan2AgentDialog(_this) {
                    if(_this.formData.applycomcode === '') {
                        _this.$message({type: 'error',message: '请先选择方案权限适用机构！'});
                        return;
                    }
                    _this.showPlan2AgentDialog = true;
            },
            queryAgent(_this) {
                $.ajax({
                    type: 'POST',
                    url: Constant.urls.queryAgentByComCode,
                    data: {
                        comCodes :  _this.$parent.formData.applycomcode
                    },
                    dataType: 'json',
                    success: function(data) {
                        if(data.state === 3) {
                            _this.$router.push('/login');
                            _this.$message({type: 'error',message: data.result});
                            return false;
                        }
                        if(data.state == 0) {
                            _this.agentOptions = data.result;
                        } else {
                          alert(data.result);
                        }
                    }
                });
                 setTimeout(function(){
                    _this.isSortRequest = true;
                },500);
            },
}

export default PlanAPI
